<?php
namespace control;
/*
*收款登记类
*/

class incomeClass extends adIndexClass
{
    private const page = 'income';
    private const table = 'payment';
    private const title = '收款登记';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('income.homeSearch.orderNo'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'payType'  => [
                        'name'  => L('income.homeSearch.payType'),
                        'width' => 200,
                    ],
                    'moneyType'         => [
                        'name'  => L('income.homeSearch.moneyType'),
                        'width' => 200,
                    ],
                    'bankName'          => [
                        'name'  => L('income.homeSearch.bankName'),
                        'width' => 200,
                    ],
                    'company'          => [
                        'name'  => L('income.homeSearch.company'),
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => L('income.homeSearch.money').'（'.static::$unit.'）',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => L('income.homeSearch.cashier'),
                        'width' => 150,
                    ],
                    'recordDate'          => [
                        'name'  => L('income.homeSearch.recordDate'),
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('income.home.orderNo') => text(array("name" => "orderNo")),
                    L('income.home.payType')   => select(["name" => "payType", 'option' => explode('，', para('payType'))]),
                    L('income.home.moneyType') => select(["name" => "moneyType", 'option' => explode('，', para('moneyType'))]),
                ],
                [
                    L('income.home.company') => text(array("name" => "company")),
                    L('income.home.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>".L('income.homeSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('income.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//编号
            "company" => $this->post('company'),//付款单位
        );
        //全等查询数组
        $equal = array(
            "moneyType" => $this->post('moneyType'),//款项类型
            "payType" => $this->post('payType'),//收款方式
            "classify" => 2,
            'coid'=>self::$coid
        );
        $and = "";
        if ($this->post('createTime')) {
            $timeArr = explode('~', $this->post('createTime'));
            $and .= " and recordDate >='{$timeArr[0]}' and recordDate <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('income.homeSearch.detail'), "click" => "newIframe('" . L('income.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('income.edit.recordDate')."：" => text(["name" => "recordDate", 'laydate' => [], 'class' => 'text', "value" => $info['recordDate']]),
                    must . L('income.edit.payType')."：" => select(["name" => "payType", 'title' => L('income.edit.payType'), 'option' => explode('，', para('payType')), 'class' => 'text', "value" => $info['payType']]),
                ],
                [
                    L('income.edit.moneyType')."：" => select(["name" => "moneyType", 'title' => L('income.edit.moneyType'), 'option' => explode('，', para('moneyType')), 'class' => 'text', "value" => $info['moneyType']]),
                    L('income.edit.invoiceNo')."：" => text(["name" => "invoiceNo", 'class' => 'text', "value" => $info['invoiceNo']]),
                ],
                [
                    L('income.edit.bankName')."：" => text(["name" => "bankName", 'class' => 'text', "value" => $info['bankName']]),
                    must . L('income.edit.company')."：" => text(["name" => "company", 'class' => 'text', "value" => $info['company']]),
                ],
                [
                    must . L('income.edit.money')."：" => text(["name" => "money", 'unit' =>  static::$unit , 'class' => 'text', "value" => $info['money']]),
                    L('income.edit.staff')."：" => selectMultiple(["name" => "managerId",'change'=>'getContract', 'title' => L('income.edit.staff'), 'table' => "staff", 'where' => "state in ('转正','试用','留职')", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['managerId']]),
                ],
                [
                    L('income.edit.contract').'：'=>"<div id='sale_contract' style='width: 100%'>".selectMultiple(array('name'=>'targetId','value'=>$info['targetId'],'title'=>L('income.edit.choice'),'sqlId'=>'id','sqlField'=>'name','table'=>'sales_contract','where'=>"salesman = '$info[managerId]' and state = '已通过' and salesman !='' and coid = '".self::$coid."'"))."</div>",
                ],
                [
                    L('income.edit.text')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);
        $html.=<<<eof
<script>
  function getContract(e){
      let stid = e.value;
      let val = $("[name='targetId]").val();
      $.post(root+'control/adIndex.html?cla=income&fun=getContract',{stid:stid,val:val},function(res) {
        $("#sale_contract").empty().append(res.html);
      },'json')
  }
</script>
eof;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 400, "html" => $html));
    }

    /**
     * 获取销售合同
     * @return bool|string
     */
    public function getContract(): bool|string
    {
        $val = $this->post('val');
        $stid = $this->post('stid');
        $json['html'] = selectMultiple(array('name'=>'targetId','value'=>$val,'title'=>L('income.edit.choice'),'sqlId'=>'id','sqlField'=>'name','table'=>'sales_contract','where'=>"salesman = '$stid' and salesman !='' and state = '已通过' order by signedDate desc"));
        return json_encode($json,320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'text' => $this->post('text'),
            'money' => $this->post('money'),
            'managerId' => $this->post('managerId'),
            'payType' => $this->post('payType'),
            'moneyType' => $this->post('moneyType'),
            'company' => $this->post('company'),
            'bankName' => $this->post('bankName'),
            'recordDate' => $this->post('recordDate'),
            'invoiceNo' => $this->post('invoiceNo'),
            'targetId' => $this->post('targetId'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'money' => L('income.editEdit.money'),
            'payType' => L('income.editEdit.payType'),
            'company' => L('income.editEdit.company'),
            'recordDate' => L('income.editEdit.recordDate'),
        ];
        $rules = [
            'money' => 'required|numeric',
            'payType' => 'required',
            'company' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('income.editEdit.power');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'YRSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, [
                    'id' => $id,
                    'classify' => 2,
                    'deptName' => $department['name'],
                    'orderNo' => $userNo,
                    'coid'=>self::$coid,
                    'stid' => $this->control['stid'],
                    'state' => '已通过',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //插入数据到收支平衡中
                $this->insetProfit($id);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('income.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     *写入到收支平衡表中
     */
    public function insetProfit($id)
    {
        $info = query(self::table, " id = '$id'");
        $profit = query('profit', " targetId = '$id'");
        if (empty($profit['id'])) {
            insert(array(
                'table' => 'profit',
                'field' => [
                    'id' => self::getId(),
                    'coid'=>self::$coid,
                    'stid' => $info['stid'],
                    'target' => '收款记录',
                    'targetId' => $info['id'],
                    'direction' => '收入',
                    'type' => $info['moneyType'] ?? '收款记录',
                    'money' => $info['money'],
                    'payDate' => $info['recordDate'],
                    'updateTime' => $this->time,
                    'time' => $this->time
                ]
            ));
        } else {
            update(array(
                'table' => 'profit',
                'field' => [
                    'money' => $info['money'],
                    'payDate' => $info['recordDate'],
                    'type' => $info['moneyType'] ?? '收款记录',
                    'updateTime' => $this->time,
                ],
                'where' => " id = '$profit[id]'"
            ));
        }
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('income.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => L('income.detail.detail'),
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => L('income.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name" => L('income.detail.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            $contract = query('sales_contract',"id = '$info[targetId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        L('income.detail.recordDate') => $info['recordDate'],
                        L('income.detail.payType') => $info['payType'],
                        L('income.detail.invoiceNo') => $info['invoiceNo'],
                        L('income.detail.staff') => self::findStaff($info['managerId']),
                    ),
                    array(
                        L('income.detail.contract') => $contract['orderNo'],
                        L('income.detail.moneyType') => $info['moneyType'],
                        L('income.detail.bankName') => $info['bankName'],
                        L('income.detail.company') => $info['company'],
                    ),
                    array(
                        L('income.detail.money')."(".static::$unit.")" => $info['money'],
                    ),
                    array(
                        L('income.detail.text') => pre($info['text'])
                    )
                ),
                L('income.detail.sys') => array(
                    array(
                        L('income.detail.orderNo') => $info['orderNo'],
                        L('income.detail.deptName') => $info['deptName'],
                        L('income.detail.stid') => self::findStaff($info['stid']),
                        L('income.detail.time') => $info['time'],
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('income.operate.msg');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('income.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('income.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('income.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");

                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //删除对应的收支平衡记录
                delete(array("table" => 'profit', "where" => " targetId = '$id' "));
                //返回
                $warn = L('income.delete.success');
                $x++;
                $text .= str_replace(['{{id}}'], [$info['id']], L('income.delete.text')) . $warn . "。<br>";


            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('income.delete.log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('income.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

